package util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;

import net.sf.json.JSONObject;
import net.sf.json.util.JSONTokener;
import base.MovieDetails;
import base.MovieInfo;

public class SearchDatabase{
	
	private String movieName;
	private String optionalYear;
	
	public SearchDatabase(String movieName, String optionalYear){
		this.movieName = movieName;
		this.optionalYear = optionalYear;
	}
	
	public MovieInfo Search() throws IOException{
		String url = Constants.URL_IMDB_SEARCH;
		if (optionalYear ==null || optionalYear.equals("")){
			url += URLEncoder.encode(movieName,"UTF-8");
		}else{
			url += URLEncoder.encode(movieName,"UTF-8") + "&year=" + URLEncoder.encode(optionalYear,"UTF-8");
		}
		System.out.println("url = " +url);
		URL serverAddress = new URL(url);
		HttpURLConnection connection = (HttpURLConnection)serverAddress.openConnection();
		InputStream is = connection.getInputStream();
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		String read;
		MovieInfo movieInfo = new MovieInfo();
		MovieDetails movieDetails = new MovieDetails();
		while ((read = reader.readLine()) != null) {
			String json = read;
			JSONObject object = (JSONObject) new JSONTokener(json).nextValue();
			if (object.containsKey("error")){
				movieInfo.setError(object.getString("error"));
			}else{
				movieInfo.setTitle((object.containsKey("title")) ? object.getString("title") : "" );
				movieDetails.setLinkToIMDB((object.containsKey("imdburl")) ? URLDecoder.decode(object.getString("imdburl"),"UTF-8") : "" );
				movieDetails.setCountry((object.containsKey("country")) ? object.getString("country") : "" );
				movieDetails.setLanguages((object.containsKey("languages")) ? niceLink(object.getString("languages")): "" );
				movieInfo.setGenre((object.containsKey("genres")) ? object.getString("genres") : "" );
				movieDetails.setRating((object.containsKey("rating")) ? object.getString("rating") : "" );
				movieDetails.setNumberofVotes((object.containsKey("votes")) ? object.getString("votes") : "" );
				movieInfo.setYear((object.containsKey("year")) ? object.getString("year") : "" );
				
				//Add Details into Movie Information
				movieInfo.setDetails(movieDetails);
			}
		}
		reader.close();
		return movieInfo;
	}
	
	public String niceLink(String str){
		while(str.indexOf("&nbsp;") > -1){
			str = str.replaceAll("&nbsp;", "");
		}
		return str;
	}
}